package com.example.screenshot;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.screenshot.util.FtpUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

public class ScreenshotService extends Service {

    private static final String TAG = "ScreenshotService";
    private static final String FTP_SERVER = "120.27.28.226";
    private static final String FTP_USERNAME = "etftp";
    private static final String FTP_PASSWORD = "yichu123";
    private static final String REMOTE_FOLDER_PATH = "map/";
    private static final int FTP_PORT = 21;
    private static final File PARENT_FILE = Environment.getExternalStoragePublicDirectory("Screenshot");


    private final Handler handler = new Handler(Looper.getMainLooper());
    @SuppressLint("SimpleDateFormat")
    private final SimpleDateFormat picNameFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
    @SuppressLint("SimpleDateFormat")
    private final SimpleDateFormat fileNameFormat = new SimpleDateFormat("yyyy-MM-dd");
    private final Timer timer = new Timer();


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler.post(() -> Toast.makeText(getApplicationContext(), "ScreenshotService Start", Toast.LENGTH_LONG).show());

        handler.postDelayed(() -> timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (isCurrentInTimeScope()) {
                    File file = new File(PARENT_FILE, fileNameFormat.format(System.currentTimeMillis()));
                    if (!file.exists()) file.mkdirs();
                    String picName = picNameFormat.format(System.currentTimeMillis()) + ".png";
                    File picFile = new File(file, picName);
                    String exec = saveScreen(picFile);
                    if (exec.isEmpty()) {
                        FtpUtil.getInstance().uploadFile(getRequest(picFile))
                                .subscribe((response, throwable) -> {
                                    if (response != null && response.success) {
                                        Log.d(TAG, response.message);
                                        picFile.delete();
                                        if (file.list() == null || file.list().length == 0)
                                            file.delete();
                                    } else if (response != null) {
                                        Log.d(TAG, response.message);
                                    } else if (throwable != null) {
                                        Log.d(TAG, throwable.getMessage());
                                    }
                                });
                    } else {
                        handler.post(() -> Toast.makeText(getApplicationContext(), "截图失败:" + exec, Toast.LENGTH_LONG).show());
                    }
                }
            }
        }, 0, 10 * 60 * 1000), getDelay());
        return super.onStartCommand(intent, flags, startId);
    }

    private static FtpUtil.Request getRequest(File picFile) {
        FtpUtil.Request request = new FtpUtil.Request();
        try {
            request.host = FTP_SERVER;
            request.port = FTP_PORT;
            request.userName = FTP_USERNAME;
            request.password = FTP_PASSWORD;
            request.remoteFolderPath = REMOTE_FOLDER_PATH + picFile.getParentFile().getName();
            request.fileName = picFile.getName();
            request.inputStream = new FileInputStream(picFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return request;
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.post(() -> Toast.makeText(getApplicationContext(), "ScreenshotService Destroy", Toast.LENGTH_LONG).show());
    }

    /**
     * delay time
     *
     * @return
     */
    private static int getDelay() {
        int delay;
        Time now = new Time();
        now.set(System.currentTimeMillis());
        if (isCurrentInTimeScope()) {
            int i = 8 - (now.minute % 10);
            if (i >= 0) {
                delay = i * 60 * 1000;
            } else {
                delay = (10 + i) * 60 * 1000;
            }
        } else {
            int hour = 10 - now.hour - 1;
            int min = 60 - now.minute + 8;
            delay = hour * 3600 * 1000 + min * 60 * 1000;
        }
        Log.d("delay", String.valueOf(delay));
        return delay;
    }

    /**
     * 判断时间是否在10：00 - 24：00之间
     *
     * @return boolean
     */
    public static boolean isCurrentInTimeScope() {
        boolean result;
        final long aDayInMillis = 1000 * 60 * 60 * 24;
        final long currentTimeMillis = System.currentTimeMillis();

        Time now = new Time();
        now.set(currentTimeMillis);

        Time startTime = new Time();
        startTime.set(currentTimeMillis);
        startTime.hour = 10;
        startTime.minute = 0;

        Time endTime = new Time();
        endTime.set(currentTimeMillis);
        endTime.hour = 24;
        endTime.minute = 0;

        if (!startTime.before(endTime)) {
            // 跨天的特殊情况（比如22:00-8:00）
            startTime.set(startTime.toMillis(true) - aDayInMillis);
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
            Time startTimeInThisDay = new Time();
            startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis);
            if (!now.before(startTimeInThisDay)) {
                result = true;
            }
        } else {
            // 普通情况(比如 8:00 - 14:00)
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
        }
        return result;
    }


    private String saveScreen(File picFile) {

        Process process = null;
        BufferedReader reader = null;
        InputStreamReader is = null;
        DataOutputStream os = null;
        String cmd = "screencap -p " + picFile.getAbsolutePath();
        try {
            process = Runtime.getRuntime().exec("su");
            is = new InputStreamReader(process.getInputStream());
            reader = new BufferedReader(is);
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            int read;
            char[] buffer = new char[4096];
            StringBuilder output = new StringBuilder();
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            process.waitFor();
            return output.toString();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}